package com.weilai.service.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.dao.ThoughtDao;
import com.weilai.domain.Thought;
import com.weilai.domain.Videos;
import com.weilai.service.ThoughtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Service
public class ThoughtServiceImpl implements ThoughtService {
    @Autowired
    private ThoughtDao thoughtDao;

    @Override
    public void add(Thought thought) {
//        //获取当前时间
//        LocalDateTime now = LocalDateTime.now();
//        Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String formattedDate = now.format(formatter);
//        thought.setCreateTime(formattedDate);
//        thought.setUpdateTime(formattedDate);
        thoughtDao.add(thought);
    }

    @Override
    public void deleteById(int id) {
        thoughtDao.deleteById(id);
    }

    @Override
    public void update(Thought thought) {
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = now.format(formatter);
        thought.setUpdateTime(formattedDate);
        thoughtDao.update(thought);
    }

    @Override
    public List<Thought> selectAllUsersThought(int userId) {
        return thoughtDao.selectAllUsersThought(userId);
    }

    @Override
    public List<Thought> selectMyAllThought(int userId) {
        return thoughtDao.selectMyAllThought(userId);
    }

    @Override
    public Thought selectById(int id) {
        return thoughtDao.selectById(id);
    }

    //在首页查询所有想法
    @Override
    public PageInfo<Thought> selectAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Thought> thought = thoughtDao.selectAll();
        return new PageInfo<>(thought);
    }

    //按userId查询想法
    @Override
    public List<Thought> selectByUserId(int userId) {
        List<Thought> thoughts = thoughtDao.selectByUserId(userId);
        return thoughts;
    }

    // 按 userid 删除想法
    @Override
    public void deleteUserById(int userId){
        try {
            thoughtDao.deleteUserById(userId);
        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_DB_ERROR, "按id删除用户信息时数据库出错");
        }
    }
}
